package org.demo.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * UDP Client
 * @author  
 * @date    2010-9-6
 * @file    org.demo.net.UDPClient.java
 */
public class UDPClient {
	// 客户端接收端口
	private static int port = 7152;
	// 数据包大小
	private static int length = 1024;
	// socket
	private DatagramSocket socket = null;
	
	/*
	 * 测试 
	 */
	public static void main(String[] args)throws Exception {
		UDPClient client = new UDPClient();
		
		String message = client.receiveMessage();
		System.out.println("message: " + message);
	}
	/**
	 * 构造函数
	 */
	public UDPClient()throws SocketException{
		// 创建 socket
		this.socket = new DatagramSocket(port);
	}
	/**
	 * 接收数据
	 * @return
	 * @throws IOException
	 */
	public String receiveMessage()throws IOException{
		// 创建数据包
		DatagramPacket pack = createDataPack(length);
		// 接收数据,会发生阻塞
		socket.receive(pack);
		
		// 接收到的数据
		byte[] data = pack.getData();
		// 接收到的数据长度
		int size = pack.getLength();
		return new String(data,0,size);
	}
	/**
	 * 构造接收数据包
	 * @param length
	 * @return
	 */
	public DatagramPacket createDataPack(int length){
		byte[] buf = new byte[length];
		DatagramPacket pack = new DatagramPacket(buf,length);
		return pack;
	}
}
